#!/bin/bash
#############
#Date 2022/1/4
#mail it-arch
#############
echo "##########################################"
echo "Auto Install l2tp                       ##"
echo "Press Ctrl + C to cancel                ##"
echo "Any key to continue                     ##"
echo "##########################################"
read -n 1
sed -i "s/SELINUX=enforcing/SELINUX=disabled/"  /etc/selinux/config
setenforce 0
PIP=`curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g'`
LIP=`ifconfig |egrep "inet addr:"|grep -v 127.0.0.1|awk '{print $2}'|cut -d: -f2`
yum install -y make gcc gmp-devel xmlto bison flex xmlto libpcap-devel lsof vim-enhanced man openswan ppp xl2tpd
read -p "Please input your l2tp username:" NAME
read -p "Please input your l2tp passwd:" PWD
cat >/etc/ipsec.conf<<EOF
config setup
    nat_traversal=yes
    virtual_private=%v4:10.0.0.0/8,%v4:xx.xx.0.0/16,%v4:xx.xx..0.0/12
    oe=off
    protostack=netkey
conn L2TP-PSK-NAT
    rightsubnet=vhost:%priv
    also=L2TP-PSK-noNAT
conn L2TP-PSK-noNAT
    authby=secret
    pfs=no
    auto=add
    keyingtries=3
    rekey=no
    ikelifetime=8h
    keylife=1h
    type=transport
    left=$PIP
    leftprotoport=17/1701
    right=%any
    rightprotoport=17/%any
EOF
cat>/etc/ipsec.secrets<<EOF
include /etc/ipsec.d/*.secrets
$PIP %any: PSK "VPNserver"
EOF
cat>>/etc/sysctl.conf<<EOF
net.ipv4.ip_forward = 1  
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.log_martians = 0
net.ipv4.conf.default.log_martians = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.icmp_ignore_bogus_error_responses = 1
EOF
sysctl -p
service ipsec start
echo "0">/proc/sys/net/ipv4/conf/default/rp_filter
echo "0">/proc/sys/net/ipv4/conf/lo/rp_filter
echo "0">/proc/sys/net/ipv4/conf/eth0/rp_filter
ipsec verify
cat >/etc/xl2tpd/xl2tpd.conf<<EOF
[lns default]
ip range = 10.10.1.100-10.10.1.250
local ip = $LIP
require chap = yes
refuse pap = yes
require authentication = yes
name = LinuxVPNserver
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
EOF
cat >/etc/ppp/chap-secrets <<EOF
$NAME *	$PWD	*
EOF
/etc/init.d/xl2tpd start
chkconfig xl2tpd on
chkconfig iptables on
chkconfig ipsec on
/etc/init.d/iptables status >/dev/null 2>&1
if [ $? -eq 0 ]
then
iptables -I INPUT -p tcp --dport 500 -j ACCEPT &&
iptables -I INPUT -p udp --dport 500 -j ACCEPT &&
iptables -I INPUT -p tcp --dport 4500 -j ACCEPT &&
iptables -I INPUT -p udp --dport 4500 -j ACCEPT &&
iptables -t nat -A POSTROUTING -s 10.10.1.0/24 -o eth0 -j MASQUERADE
iptables -I FORWARD -s 10.10.1.0/24 -j ACCEPT
iptables -I FORWARD -d 10.10.1.0/24 -j ACCEPT
service iptables save
service iptables restart 
else
	echo -e "\033[32m iptables is stopd\033[0m"
fi
echo -e "\033[32m l2tp is install success! IP:$PIP vpnusername:$NAME vpnpassword:$PWD shared key:VPNserver\033[0m"
